package com.modelmetrics.controls
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.ComboBox;
	import mx.events.ListEvent;
	
	[Event( name="selectedValueChange",type="mx.events.ListEvent" )]
	
	public class ComboBox extends mx.controls.ComboBox
	{
		private var bSelectedValueSet:Boolean = false;
		private var _selectedValue:String;
		public function set selectedValue(s:String):void
		{
			bSelectedValueSet 	= true;
			_selectedValue 		= s;
			invalidateProperties();
		}
		public function get selectedValue():String {return _selectedValue;}
		
		private var _useLowerCaseValue:Boolean;
		public function set useLowerCaseValue( value:Boolean ):void
		{
			_useLowerCaseValue = value;
			bSelectedValueSet = true;
			invalidateProperties();
		}
		
		public function get useLowerCaseValue():Boolean
		{
			return _useLowerCaseValue;
		}
		

		public var dataField:String;
		

		override protected function commitProperties():void
		{
			// invoke ComboBox version
			super.commitProperties();
		
			// If value set and have dataProvider
			if( bSelectedValueSet && dataProvider.length )
			{
				// Set flag to false so code won't be called until selectedValue is set again
				bSelectedValueSet=false;
				// Loop through dataProvider
				for (var i:int=0;i<this.dataProvider.length;i++)
				{
					// Get this item's data
					var item:String;
					if( dataProvider is ArrayCollection )
					{
						if( dataField )
							item = this.dataProvider.getItemAt(i)[dataField];
						else
							item = this.dataProvider.getItemAt(i);
					}
					else if( dataProvider is Array )
					{
						if( dataField )
							item = this.dataProvider[i][dataField];
						else
							item = this.dataProvider[i];
							
					}
					
					if( useLowerCaseValue )
					{
						item 			= item.toLowerCase();
						_selectedValue	= _selectedValue.toLowerCase();
					}
						
						
					
					// Check if is selectedValue
					if( item == _selectedValue )
					{
						// Yes, set selectedIndex
						this.selectedIndex = i;
						this.dispatchEvent( new ListEvent('selectedValueChange',false,false,-1,this.selectedIndex) );
						break;
					}
				}
			}
		}

	}
}